home *** CD-ROM | disk | FTP | other *** search
- Path: mother.usf.edu!news
- From: yatesc@csee.usf.edu (Randy Yates)
- Newsgroups: comp.lang.c
- Subject: Re: Finding a prime number
- Date: 6 Feb 1996 14:02:32 GMT
- Organization: University of South Florida
- Message-ID: <4f7n1o$ol9@mother.usf.edu>
- References: <4e875s$nqk@reader2.ix.netcom.com> <7c8_9601301722@tor250.org>
- NNTP-Posting-Host: ppp78.cfr.usf.edu
- Mime-Version: 1.0
- X-Newsreader: WinVN 0.93.14
-
- In article <7c8_9601301722@tor250.org>, Andrew.Frank@fknights.gryn.org says...
- >
- >As advtr@ix.netcom.com had made knowen to All, on 25 Jan 96 10:21:32, I
- >quote.
- > ad> From: advtr@ix.netcom.com(Advance Trading)
- > ad> Subject: Finding a prime number
- > ad> Organization: Netcom
- >
- > ad> I need to write a function that will find wether or not a number is
- > ad> prime. I can come close but I get numbers that are not prime with the
- > ad> prime numbers.
- >
- > I recently wrote a program to do this. It will take about 10
- > seconds to process a little at the start, but will then quickly tell
- > if any number between 4 and 4.2 billion is prime. Here is the
- > source code.
-
- Here is code that does not take a long time to start up and tests
- for primes in the range of unsigned long integers. The longest
- I've seen it run is for about 3 seconds when finding a prime
- around 1 billion:
-
-
-
- #include<math.h>
- #include<stdlib.h>
- #include<fstream.h>
-
- /******************************************************
- Programmer: R. Yates
- Date: 2-4-96
- Function: isprime
-
- Description:
-
- Determines if the passed integer is prime.
-
- Usage:
-
- isprime int
-
- where int is a positive integer greater than 1.
- ********************************************************/
-
- /* Command Line Usage Message */
- void clusage()
- {
- cout << "ISPRIME integer\n";
- cout << " integer = a positive integer greater than 1\n";
- }
-
- long gcd(long a, long b)
- {
- long r0, r1, r2, q, r1last;
-
- r0 = a;
- r1 = b;
- r2 = 1;
- while (r2 != 0)
- {
- r2 = r0 % r1;
- r0 = r1;
- r1last = r1;
- r1 = r2;
- }
- return r1last;
- }
-
- void main(int argc, char *argv[])
- {
- long primecheck, curcheck, maxcheck;
- //, firstprimes[10]={2,3,5,7,11,13,17,19,23,29};
-
- /* Parse the command line parameters: */
- if (argc < 2)
- {
- clusage();
- return;
- }
-
- primecheck = atol(argv[1]);
- if (primecheck < 2)
- {
- cout << "Error: integer must be greater than 1\n";
- clusage();
- return;
- }
-
- curcheck=2;
- maxcheck = ceil(sqrt(primecheck));
- while (curcheck <= maxcheck)
- {
- if (gcd(primecheck, curcheck) != 1)
- {
- cout << "Not prime, " << curcheck << " is a divisor\n";
- return;
- }
- curcheck++;
- }
- cout << "Prime\n";
- }
-
-
-
-
-
-
- --
- % Randy Yates % "...the answer lies within your soul
- % EE/Mathematics Student % 'cause no one knows which side
- % University of South Florida % the coin will fall."
- % <yatesc@csee.usf.edu> % 'Big Wheels', *Out of the Blue*, ELO
-
-